package com.huawei.hwshare.third.slice;

import com.huawei.hwshare.third.MainAbility;
import com.huawei.hwshare.third.ResourceTable;
//import com.huawei.hwshare.third.ShareFaManager;
import com.huawei.hwshare.third.ShareFaManager;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileDescriptor;
import ohos.interwork.utils.PacMapEx;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;
import java.io.*;

public class MainAbilitySlice extends AbilitySlice {
    private static  final int imgRequestCode = 1001;
    //核心: 显示分享的图片
    private Image photo;
    private Uri  uri;
    private byte [] picByte;
    InputStream resource;
    private Image cardimage;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Button btn = (Button) findComponentById(ResourceTable.Id_btn);
        Button btn1 = (Button) findComponentById(ResourceTable.Id_btn1);
        cardimage = (Image) findComponentById(ResourceTable.Id_cardimg1);

        btn1.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                selectPhoto();
            }
        });
        photo = (Image) findComponentById(ResourceTable.Id_photo);
        btn.setClickedListener(new Component.ClickedListener() {
            @Override
            /*华为分享功能的核心代码*/
            public void onClick(Component component) {
                /*数据包*/
                PacMapEx pacMap = new PacMapEx();
                /*分享的服务类型 默认为0 当前也仅支持0*/
                pacMap.putObjectValue(ShareFaManager.SHARING_FA_TYPE, 0);
                /*分享服务的包名，必选参数*/
                pacMap.putObjectValue(ShareFaManager.HM_BUNDLE_NAME, getBundleName());
                /*额外的信息 非必选*/
                pacMap.putObjectValue(ShareFaManager.SHARING_EXTRA_INFO, "原子化服务分享");
                /*分享的服务的Ability类名，必选参数*/
                pacMap.putObjectValue(ShareFaManager.HM_ABILITY_NAME, MainAbility.class.getName());
                /*卡片展示的服务介绍信息，必须参数*/
                pacMap.putObjectValue(ShareFaManager.SHARING_CONTENT_INFO, "分享成功！");
                /*卡片展示服务介绍图片，最大长度153600，必选参数。*/
                pacMap.putObjectValue(ShareFaManager.SHARING_THUMB_DATA, picByte);
                // byte[] iconImg = getResourceBytes(ResourceTable.Media_icon);
                /*服务图标  非必选参数*/
                //pacMap.putObjectValue(com.huawei.hwshare.third.ShareFaManager.HM_FA_ICON, iconImg);
                // pacMap.putObjectValue(com.huawei.hwshare.third.ShareFaManager.HM_FA_ICON, iconByte);
                /*卡片展示的服务名称*/
                pacMap.putObjectValue(ShareFaManager.HM_FA_NAME, "华为分享服务测试");
                // 第一个参数为appid，在华为AGC创建原子化服务时自动生成。
                ShareFaManager.getInstance(MainAbilitySlice.this).shareFaInfo("942536802034526976", pacMap);
            }
        });

    }
    private byte[] getResourceBytes(int resId) {

        ByteArrayOutputStream outStream = null;

        try {
            resource = getResourceManager().getResource(resId);
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = resource.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            outStream.close();
            resource.close();
            return outStream.toByteArray();
        } catch (IOException | NotExistException e) {
            // HiLog.error(TAG, "get resource occurs io exception!");
        } finally {
            if (resource != null) {
                try {
                    resource.close();
                } catch (IOException e) {
                    //   HiLog.error(TAG, "close input stream occurs io exception!");
                }
            }
            if (outStream != null) {
                try {
                    resource.close();
                } catch (IOException e) {
                    //  HiLog.error(TAG, "close output stream occurs io exception!");
                }
            }
        }
        return null;
    }

    //选择图片
    private void selectPhoto() {
        //调起系统的选择来源数据视图
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
        intent.setOperation(opt);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent, imgRequestCode);
    }
    /*选择图片回调*/
    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        if(requestCode==imgRequestCode && resultData!=null)
        {
            //被选择的图片的uri地址
            String img_uri=resultData.getUriString();
            //定义数据能力帮助对象
            DataAbilityHelper helper=DataAbilityHelper.creator(getContext());
            //定义图片来源对象
            ImageSource imageSource = null;
            //选择的Img对应的Id
            String img_id=null;
            /*
             *如果是选择文件则getUriString结果为dataability:///com.android.providers.media.documents/document/image%3A437，其中%3A437是":"的URL编码结果，后面的数字就是image对应的Id
             */
            /*
             *如果选择的是图库则getUriString结果为dataability:///media/external/images/media/262，最后就是image对应的Id
             */
            //判断是选择了文件还是图库
            if(img_uri.lastIndexOf("%3A")!=-1){
                img_id = img_uri.substring(img_uri.lastIndexOf("%3A")+3);
            }
            else {
                img_id = img_uri.substring(img_uri.lastIndexOf('/')+1);
            }
            //获取图片对应的uri，前缀是content，替换成对应的dataability前缀
            uri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,img_id);
            try {
                //读取图片
                FileDescriptor fd = helper.openFile(uri, "r");
                //RawFileDescriptor rfd = helper.openRawFile(uri,"r");
                imageSource = ImageSource.create(fd, null);
                //创建位图
                PixelMap pixelMap = imageSource.createPixelmap(null);
                //组件显示选择的图片
                photo.setPixelMap(pixelMap);
                picByte = new byte[153600];
                //打包图片
                ImagePacker packer = null;
                try{
                    packer= ImagePacker.create();
                    ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
                    //图片格式信息
                    packingOptions.format = "image/jpeg";
                    //图片质量
                    packingOptions.quality = 90;
                    //打包
                    packer.initializePacking(picByte, packingOptions);
                    packer.addImage(pixelMap);
                    //完成打包
                    packer.finalizePacking();


                }finally {
                    packer.release();

                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (imageSource != null) {
                    imageSource.release();
                }
            }
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
